import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 邮箱工具类
 */
@Slf4j
@Service
public class SendEmailUtil {



    @Value(value = "${mailtwo}")
    private String mailtwo;

    /**
     * 发送邮件 (阿里云邮箱企业版)
     *
     * @param toEmail 接收邮箱
     * @param title   发送主题
     * @param centent 发送内容
     * @throws Exception
     */
    public void sendMail(String toEmail, String title, String centent) throws Exception {
        String emailName = "service@waimao369.com";
        String emailPassword = "dakj@2021";//密码

        Properties prop = new Properties();
        if (mailtwo.equals("dev")) {
            prop.put("mail.smtp.host", "smtp.qiye.aliyun.com");
            prop.put("mail.transport.protocol", "smtp");
            prop.put("mail.smtp.auth", "true");
        }

        if (mailtwo.equals("prod")) {
            prop.put("mail.smtp.host", "smtp.qiye.aliyun.com");
            prop.put("mail.transport.protocol", "smtp");
            prop.put("mail.smtp.auth", "true");
            prop.put("mail.smtp.port", "456");
            prop.put("mail.smtp.socketFactory.port", "465");
            prop.put("mail.smtp.socketFactory.class",
                    "javax.net.ssl.SSLSocketFactory");
        }

        Session session = Session.getInstance(prop);
        session.setDebug(true);
        Transport ts = session.getTransport();
        ts.connect(emailName, emailPassword);
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(emailName));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        message.setSubject(title);
        message.setContent(centent, "text/html;charset=utf-8");
        ts.sendMessage(message, message.getAllRecipients());
        log.info("邮箱开始......................");
    }

//    public static void main(String[] args) {
//
//		try {
//			sendMail("17853147768@163.com", "测试", "test");
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
}
